package com.rawchen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rawchen.config.RedisKeyConfig;
import com.rawchen.entity.Tag;
import com.rawchen.exception.NotFoundException;
import com.rawchen.exception.PersistenceException;
import com.rawchen.mapper.TagMapper;
import com.rawchen.service.RedisService;
import com.rawchen.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description: 博客标签业务层实现
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements TagService {
	@Autowired
	private TagMapper tagMapper;
	@Autowired
	private RedisService redisService;

	@Override
	public List<Tag> getTagList() {
		LambdaQueryWrapper<Tag> lqw = new LambdaQueryWrapper<Tag>().orderByDesc(Tag::getId);
		return tagMapper.selectList(lqw).stream().peek(tag -> tag.setBlogs(null)).toList();
	}

	@Override
	public List<Tag> getTagListNotId() {
		String redisKey = RedisKeyConfig.TAG_CLOUD_LIST;
		List<Tag> tagListFromRedis = redisService.getListByValue(redisKey);
		if (tagListFromRedis != null) {
			return tagListFromRedis;
		}
		List<Tag> tagList = tagMapper.getTagListNotId();
		redisService.saveListToValue(redisKey, tagList);
		return tagList;
	}

	@Override
	public List<Tag> getTagListByBlogId(Long blogId) {
		return tagMapper.getTagListByBlogId(blogId);
	}

	@Transactional
	@Override
	public void saveTag(Tag tag) {
		if (tagMapper.insert(tag) != 1) {
			throw new PersistenceException("标签添加失败");
		}
		redisService.deleteCacheByKey(RedisKeyConfig.TAG_CLOUD_LIST);
	}

	@Override
	public Tag getTagById(Long id) {
		Tag tag = tagMapper.selectById(id);
		if (tag == null) {
			throw new NotFoundException("标签不存在");
		}
		return tag;
	}

	@Override
	public Tag getTagByName(String name) {
		LambdaQueryWrapper<Tag> lqw = new LambdaQueryWrapper<Tag>().eq(Tag::getName, name);
		return tagMapper.selectOne(lqw); //tag的name为unique键，不会抛异常
	}

	@Transactional
	@Override
	public void deleteTagById(Long id) {
		if (tagMapper.deleteById(id) != 1) {
			throw new PersistenceException("标签删除失败");
		}
		redisService.deleteCacheByKey(RedisKeyConfig.TAG_CLOUD_LIST);
	}

	@Transactional
	@Override
	public void updateTag(Tag tag) {
		if (tagMapper.updateById(tag) != 1) {
			throw new PersistenceException("标签更新失败");
		}
		redisService.deleteCacheByKey(RedisKeyConfig.TAG_CLOUD_LIST);
		//修改了标签名或颜色，可能有首页文章关联了标签，也要更新首页缓存
		redisService.deleteCacheByKey(RedisKeyConfig.HOME_BLOG_INFO_LIST);
	}
}
